package com.vitas.coin.util;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;

import com.huawei.hms.audioeditor.sdk.AudioExtractCallBack;
import com.huawei.hms.audioeditor.sdk.HAEAudioExpansion;
import com.huawei.hms.audioeditor.sdk.LaunchCallback;
import com.huawei.hms.audioeditor.ui.api.AudioEditorLaunchOption;
import com.huawei.hms.audioeditor.ui.api.AudioExportCallBack;
import com.huawei.hms.audioeditor.ui.api.AudioInfo;
import com.huawei.hms.audioeditor.ui.api.HAEUIManager;
import com.huawei.hms.audioeditor.ui.api.MenuCommon;
import com.snap.util.Util;
import com.vitas.coin.MyApp;
import com.vitas.coin.data.bean.ChildrenVoiceBean;
import com.vitas.coin.data.bean.DownloadedBean;
import com.vitas.coin.db.DownDao;
import com.vitas.coin.task.SilentTask;
import com.vitas.coin.task.TaskEngine;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import kotlin.Unit;
import kotlin.jvm.functions.Function2;

public class Audio {

    public static void openEdit(Activity activity, String path, String name) {
        // 不带入参的启动方式
//        HAEUIManager.getInstance().launchEditorActivity(activity);
//        if (true) {
//            return;
//        }
// 一级菜单列表（以下菜单列表仅为部分示例）
        ArrayList menuList = new ArrayList<>();
        menuList.add(MenuCommon.MAIN_MENU_ADD_AUDIO_CODE);
        menuList.add(MenuCommon.MAIN_MENU_AUDIO_RECORDER_CODE);
// 二级菜单列表（以下菜单列表仅为部分示例）
        ArrayList secondMenuList = new ArrayList<>();
        secondMenuList.add(MenuCommon.EDIT_MENU_SPLIT_CODE);
        secondMenuList.add(MenuCommon.EDIT_MENU_DEL_CODE);
        secondMenuList.add(MenuCommon.EDIT_MENU_VOLUME2_CODE);

        AudioInfo info = new AudioInfo(path);
        info.setAudioName(name);
        ArrayList<AudioInfo> files = new ArrayList();
        files.add(info);

// 自定义导出路径
        String exportPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getPath() + "/myAudio";
        new File(exportPath).mkdirs();
        AudioEditorLaunchOption.Builder audioEditorLaunch = new AudioEditorLaunchOption.Builder()
                // 设置一级菜单
                .setCustomMenuList(menuList)
                // 设置二级菜单
                .setSecondMenuList(secondMenuList)
                // 设置草稿ID，音频编辑支持草稿模式，通过在AudioEditorLaunchOption中设置draftId来指定草稿
//                .setDraftId("xxxxxxxxx2f64fcc8996d0b04fxxxxxx")
                // 设置草稿模式，默认值为NOT_SAVE
                .setDraftMode(AudioEditorLaunchOption.DraftMode.NOT_SAVE)
                // 设置音频文件路径
                .setFilePaths(files)
                // 设置导出路径
                .setExportPath(exportPath);
        // 带菜单列表以及音频文件路径的启动方式
        try {
            HAEUIManager.getInstance().launchEditorActivity(activity, audioEditorLaunch.build(), new LaunchCallback() {
                @Override
                public void onFailed(int errCode, String errMsg) {
                    Toast.makeText(activity, errMsg, Toast.LENGTH_SHORT).show();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void setCallback() {
        HAEUIManager.getInstance().setCallback(new AudioExportCallBack() {
            @Override
            public void onAudioExportSuccess(AudioInfo audioInfo) {
                List<Activity> list = ((MyApp) Util.INSTANCE.getApp()).getAct();
                List<Activity> tmp = new ArrayList<>();
                for (Activity ac : list) {
                    if (ac.getClass().getName().contains("com.huawei")) {
                        tmp.add(ac);
                    }
                }
                for (Activity ac : tmp) {
                    ac.finish();
                }
            }

            @Override
            public void onAudioExportFailed(int i) {

            }
        });
    }

    public static void editAudio(ChildrenVoiceBean bean, FragmentActivity activity) {
        if (bean.getVoiceUrl().startsWith("file://")) {
            if (Utils.INSTANCE.checkRight(activity)) {
                Audio.openEdit(activity, Uri.parse(bean.getVoiceUrl()).getPath(), bean.getName());
            }
            return;
        }
        Handler h = new Handler(Looper.getMainLooper());
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                DownloadedBean tmp = new DownDao().get(bean.getId());
                if (tmp != null) {
                    h.post(() -> {
                        if (Utils.INSTANCE.checkRight(activity)) {
                            Audio.openEdit(activity, tmp.path, bean.getName());
                        }
                    });
                } else {
                    h.post(() -> {
                        Utils.INSTANCE.download(activity, bean, 1, new Function2<String, String, Unit>() {
                            @Override
                            public Unit invoke(String s, String s2) {
                                h.post(() -> Audio.openEdit(activity, s2, s));
                                return null;
                            }
                        }, null);
                    });
                }
            }
        });
    }

    public static void export(Context context, String inVideoPath, String outAudioDir, String outAudioName, AudioExtractCallBack callback) {
        // outAudioDir提取出的音频保存的文件夹路径，非必填
        // outAudioName提取出的音频名称，不带后缀，非必填
        HAEAudioExpansion.getInstance().extractAudio(context, inVideoPath, outAudioDir, outAudioName, callback);
    }
}
